// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MatrixFramework.Keycloak.Abstractions.Options;
using MatrixFramework.Keycloak.Abstractions.Services;

namespace MatrixFramework.Keycloak.Services;

/// <summary>
/// Keycloak HTTP客户端工厂实现
/// </summary>
public class KeycloakClientFactory : IKeycloakClientFactory
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IOptionsMonitor<KeycloakOptions> _options;
    private readonly ILogger<KeycloakClientFactory> _logger;

    public KeycloakClientFactory(
        IHttpClientFactory httpClientFactory,
        IOptionsMonitor<KeycloakOptions> options,
        ILogger<KeycloakClientFactory> logger)
    {
        _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
        _options = options ?? throw new ArgumentNullException(nameof(options));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public HttpClient CreateClient()
    {
        var client = _httpClientFactory.CreateClient("Keycloak");
        ConfigureClient(client);
        return client;
    }

    public HttpClient CreateAuthenticatedClient(string realmName)
    {
        var client = _httpClientFactory.CreateClient($"Keycloak-{realmName}");
        ConfigureClient(client);
        // TODO: 添加认证逻辑
        return client;
    }

    private void ConfigureClient(HttpClient client)
    {
        var options = _options.CurrentValue;
        client.BaseAddress = new Uri(options.BaseUrl);
        client.DefaultRequestHeaders.Add("User-Agent", "MatrixFramework.Keycloak/1.0");
        client.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);
    }
}
